package com.stock.api.shiro;

import com.stock.api.dto.sys.SysMenuDto;
import com.stock.api.service.sys.SysMenuService;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.factory.FactoryBean;

import javax.annotation.Resource;
import java.util.List;

public class DynamicUrls implements FactoryBean<Section> {

    //在项目启动的时候，加载配置文件上的 约束配置
    private String filterChainDefinitions;

    private SysMenuService sysMenuService;

    /**
     * 在这里我们可以从数据库中获取相关权限，再存放进section中
     */
    @Override
    public Section getObject() throws Exception {
        Ini ini = new Ini();
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        //只有超级管理员才能查看druid监控器
        section.put("/druid/**", "roles[1]");
        //除了anon,所有请求都需要进行登录验证
        section.put("/**", "authc");
        //初始化菜单对应的角色
        initSection(section);
        return section;
    }

    /**
     * 初始化菜单对应的角色
     *
     * @param section
     */
    private void initSection(Ini.Section section) {
        //获取所有菜单对应的角色
        List<SysMenuDto> list = sysMenuService.selectMenuRole();
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getUrl().startsWith("/")) {
                    section.put(list.get(i).getUrl(), "roles[" + list.get(i).getRoleId() + "]");
                } else {
                    section.put("/" + list.get(i).getUrl(), "roles[" + list.get(i).getRoleId() + "]");
                }
            }
        }
    }

    @Override
    public Class<?> getObjectType() {
        return Section.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }

    public void setSysMenuService(SysMenuService sysMenuService) {
        this.sysMenuService = sysMenuService;
    }
}
